package org.homeworkadmin.admin.controller;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/img")
public class ImageController {

    private static final String UPLOAD_IMG = "E:\\files";

    /**
     * 根据文件名返回图片文件
     *
     * @param url 图片文件名
     * @return 图片文件或者错误信息
     */
    @GetMapping("/get")
    public ResponseEntity<?> getImage(@RequestParam("url") String url) {
        // 拼接文件路径
        Path imagePath = Paths.get(UPLOAD_IMG, url);

        try {
            // 检查文件是否存在
            Resource resource = new UrlResource(imagePath.toUri());
            if (resource.exists() && resource.isFile()) {
                // 设置 HTTP 头信息
                HttpHeaders headers = new HttpHeaders();
                headers.add(HttpHeaders.CONTENT_TYPE, "image/jpeg"); // 默认设置为 JPEG 图片类型
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + url + "\"");

                return ResponseEntity.ok()
                        .headers(headers)
                        .body(resource);
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body("图片文件不存在");
            }
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("文件读取错误: " + e.getMessage());
        }
    }
}
